/**
 * 通知系统测试模块
 * 整合了所有通知相关的测试功能
 */

import React, { useState } from 'react';
import { Card, Button, Space, Typography, Alert, Input, Select, Row, Col, Divider, Form } from 'antd';
import {
  UploadOutlined,
  DownloadOutlined,
  SyncOutlined,
  DatabaseOutlined,
  BarChartOutlined,
  SaveOutlined,
  ImportOutlined,
  ExportOutlined,
  BellOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  CloseCircleOutlined,
  InfoCircleOutlined,
} from '@ant-design/icons';

import { useNotificationManager, createQuickNotifications } from '../../../utils/notificationHelpers';
import { NotificationType } from '../../../types/notification';
import { showNotification } from '../../../utils/notification';

const { Title, Paragraph, Text } = Typography;
const { Option } = Select;

const NotificationTests: React.FC = () => {
  const notificationManager = useNotificationManager();
  const quickNotifications = createQuickNotifications();
  
  const [fileName, setFileName] = useState('example.xlsx');
  const [fileSize, setFileSize] = useState(1024 * 1024 * 5); // 5MB
  const [dataSource, setDataSource] = useState('MySQL数据库');
  const [targetSource, setTargetSource] = useState('Redis缓存');
  const [currentNotificationId, setCurrentNotificationId] = useState<string | null>(null);
  const [customTitle, setCustomTitle] = useState('');
  const [customDescription, setCustomDescription] = useState('');

  // 文件上传示例
  const handleFileUpload = () => {
    const uploadId = notificationManager.createFileUpload(fileName, fileSize);
    setCurrentNotificationId(uploadId);
    
    let progress = 0;
    const interval = setInterval(() => {
      progress += 10;
      notificationManager.updateProgress(
        uploadId,
        progress,
        `上传中 ${progress}%`,
        `${Math.round(fileSize * progress / 100 / 1024 / 1024 * 100) / 100} MB`
      );
      
      if (progress >= 100) {
        clearInterval(interval);
        notificationManager.complete(uploadId, true, '文件上传成功');
        setCurrentNotificationId(null);
      }
    }, 500);
  };

  // 文件下载示例
  const handleFileDownload = () => {
    const downloadId = notificationManager.createFileDownload(fileName, fileSize);
    setCurrentNotificationId(downloadId);
    
    let progress = 0;
    const interval = setInterval(() => {
      progress += 15;
      notificationManager.updateProgress(
        downloadId,
        progress,
        `下载中 ${progress}%`,
        `剩余时间: ${Math.ceil((100 - progress) / 15)} 秒`
      );
      
      if (progress >= 100) {
        clearInterval(interval);
        notificationManager.complete(downloadId, true, '文件下载完成');
        setCurrentNotificationId(null);
      }
    }, 800);
  };

  // 数据同步示例
  const handleDataSync = () => {
    const syncId = notificationManager.createDataSync(dataSource, targetSource);
    setCurrentNotificationId(syncId);
    
    let progress = 0;
    const steps = ['连接数据源', '读取数据', '转换格式', '写入目标', '验证数据'];
    
    const interval = setInterval(() => {
      progress += 20;
      const stepIndex = Math.floor(progress / 20) - 1;
      const currentStep = steps[stepIndex] || '完成';
      
      notificationManager.updateProgress(
        syncId,
        progress,
        currentStep,
        `${Math.floor(progress / 20)}/${steps.length} 步骤`
      );
      
      if (progress >= 100) {
        clearInterval(interval);
        notificationManager.complete(syncId, true, '数据同步完成', {
          synced: 1250,
          errors: 0
        });
        setCurrentNotificationId(null);
      }
    }, 1000);
  };

  // 简单通知示例
  const handleSimpleNotification = (type: NotificationType) => {
    const titles = {
      info: '信息通知',
      warning: '警告通知',
      error: '错误通知',
      success: '成功通知',
    };
    
    showNotification(type, titles[type as keyof typeof titles] || '通知', `这是一个${type}类型的通知示例`);
  };

  // 控制操作
  const handlePause = () => {
    if (currentNotificationId) {
      notificationManager.pause(currentNotificationId, undefined, '用户暂停');
    }
  };

  const handleResume = () => {
    if (currentNotificationId) {
      notificationManager.resume(currentNotificationId, undefined, '用户恢复');
    }
  };

  const handleCancel = () => {
    if (currentNotificationId) {
      notificationManager.cancel(currentNotificationId, '用户取消操作');
      setCurrentNotificationId(null);
    }
  };

  const handleClearCompleted = () => {
    notificationManager.clearCompleted();
  };

  return (
    <div>
      <Alert
        message="通知系统说明"
        description="DataPlexus采用智能显示策略：简单通知（info/success/warning/error）仅显示ant-notification，进度通知（upload/download/processing等）显示在Dynamic Island中。"
        type="info"
        showIcon
        style={{ marginBottom: 24 }}
      />

      {/* 简单通知测试 */}
      <Card title="简单通知测试" style={{ marginBottom: 16 }}>
        <Paragraph type="secondary">
          这些通知会显示在页面右上角，3-5秒后自动消失：
        </Paragraph>
        <Space wrap>
          <Button 
            icon={<InfoCircleOutlined />} 
            onClick={() => handleSimpleNotification('info')}
          >
            信息通知
          </Button>
          <Button 
            icon={<CheckCircleOutlined />} 
            type="primary" 
            onClick={() => handleSimpleNotification('success')}
          >
            成功通知
          </Button>
          <Button 
            icon={<ExclamationCircleOutlined />} 
            danger 
            onClick={() => handleSimpleNotification('warning')}
          >
            警告通知
          </Button>
          <Button 
            icon={<CloseCircleOutlined />} 
            danger 
            onClick={() => handleSimpleNotification('error')}
          >
            错误通知
          </Button>
        </Space>
      </Card>

      {/* 进度通知测试 */}
      <Card title="进度通知测试（Dynamic Island）" style={{ marginBottom: 16 }}>
        <Paragraph type="secondary">
          这些通知会显示在Header的Dynamic Island中，支持进度显示和用户交互：
        </Paragraph>
        
        <Row gutter={16}>
          <Col xs={24} sm={12} md={8}>
            <Card size="small" title="文件操作">
              <Space direction="vertical" style={{ width: '100%' }}>
                <Input 
                  placeholder="文件名" 
                  value={fileName} 
                  onChange={(e) => setFileName(e.target.value)}
                />
                <Space>
                  <Button 
                    icon={<UploadOutlined />} 
                    onClick={handleFileUpload}
                    disabled={!!currentNotificationId}
                  >
                    上传
                  </Button>
                  <Button 
                    icon={<DownloadOutlined />} 
                    onClick={handleFileDownload}
                    disabled={!!currentNotificationId}
                  >
                    下载
                  </Button>
                </Space>
              </Space>
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={8}>
            <Card size="small" title="数据同步">
              <Space direction="vertical" style={{ width: '100%' }}>
                <Select 
                  value={dataSource} 
                  onChange={setDataSource}
                  style={{ width: '100%' }}
                >
                  <Option value="MySQL数据库">MySQL数据库</Option>
                  <Option value="PostgreSQL">PostgreSQL</Option>
                  <Option value="MongoDB">MongoDB</Option>
                </Select>
                <Button 
                  icon={<SyncOutlined />} 
                  onClick={handleDataSync}
                  disabled={!!currentNotificationId}
                  block
                >
                  开始同步
                </Button>
              </Space>
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={8}>
            <Card size="small" title="操作控制">
              <Space direction="vertical" style={{ width: '100%' }}>
                <Button 
                  onClick={handlePause}
                  disabled={!currentNotificationId}
                  block
                >
                  暂停
                </Button>
                <Button 
                  onClick={handleResume}
                  disabled={!currentNotificationId}
                  block
                >
                  恢复
                </Button>
                <Button 
                  danger
                  onClick={handleCancel}
                  disabled={!currentNotificationId}
                  block
                >
                  取消
                </Button>
              </Space>
            </Card>
          </Col>
        </Row>
      </Card>

      {/* 自定义通知测试 */}
      <Card title="自定义通知测试">
        <Form layout="vertical">
          <Row gutter={16}>
            <Col xs={24} sm={12}>
              <Form.Item label="通知标题">
                <Input 
                  placeholder="输入通知标题" 
                  value={customTitle}
                  onChange={(e) => setCustomTitle(e.target.value)}
                />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item label="通知描述">
                <Input 
                  placeholder="输入通知描述" 
                  value={customDescription}
                  onChange={(e) => setCustomDescription(e.target.value)}
                />
              </Form.Item>
            </Col>
          </Row>
          <Space>
            <Button 
              type="primary"
              onClick={() => customTitle && notificationManager.createNotification({
                title: customTitle,
                description: customDescription,
                type: 'info',
                persistent: true,
                autoClose: false,
              })}
              disabled={!customTitle.trim()}
            >
              创建持久通知
            </Button>
            <Button
              onClick={() => customTitle && showNotification('info', customTitle, customDescription)}
              disabled={!customTitle.trim()}
            >
              创建临时通知
            </Button>
            <Button
              danger
              onClick={handleClearCompleted}
            >
              清除已完成
            </Button>
          </Space>
        </Form>
      </Card>
    </div>
  );
};

export default NotificationTests;
